/*
    \brief     SPI flash write/read test demo. 
*/

#include <stdio.h>

#include "nuclei_sdk_hal.h"
#include "P25Q80L.h"


int main(void)
{	
	uint16_t i=0;
	uint16_t ReadValue=0;	
	uint16_t ID_Read=0;
 
 	uint8_t Data_Array[256]={0};
	uint8_t datatemp0[256]={0}; 	
	uint8_t datatemp1[256]={0};
	uint8_t datatemp2[256]={0};
 	for(i=0; i<256; i++)
 	{
 		Data_Array[i]=i;
		// datatemp[i]  =0;
	}

	Data_Array[0]  =2 ;	Data_Array[1]  =0;	Data_Array[2]   =2 ;   Data_Array[3]   =1;	
	Data_Array[4]  =0 ;	Data_Array[5]  =4;	Data_Array[6]   =2 ;   Data_Array[7]   =5;
	Data_Array[8]  =1 ;	Data_Array[9]  =5;	Data_Array[10]  =1 ;   Data_Array[11]  =9;

	/*step1, flash device init*/ 
	P25Q80L_Init();			//P25Q80L初始化	

#if 1
	// Set Single-SPI mode read FLASH ID.
	ID_Read=P25Q80L_SReadID();
	anl_printf("%x\r\n",ID_Read);

	/*step2, flash ID check*/
	while(ID_Read != P25Q80L_ID)
	{
		anl_printf("P25Q80L Check Failed!\r\n");
		anl_printf("Please Check! \r\n");
		delay_1ms(500);
	}
	anl_printf("P25Q80L ID Check Pass!\r\n");
#endif

#if 0
	//Set Quad-SPI mode read FLASH ID.
	ID_Read=P25Q80L_QReadID();		
	anl_printf("%x\r\n",ID_Read);

	/*step2, flash ID check*/
	while(ID_Read != P25Q80L_ID)
	{
		anl_printf("P25Q80L Check Failed!\r\n");
		anl_printf("Please Check! \r\n");
		delay_1ms(500);
	}
	anl_printf("P25Q80L ID Check Pass!\r\n");
//#endif

	// Update flash (erase+write)
	anl_printf("Start Write P25Q80L:\r\n");
	P25Q80L_Write((uint8_t*)Data_Array,0x000000,256);
	anl_printf("P25Q80L Write Finished!\r\n");
 
	//Single-SPI mode
	anl_printf("Start Single-Read P25Q80L....!\r\n");
	P25Q80L_Read((uint8_t*)datatemp0,0x000000,256);			 
 	for(i=0; i<256; i++)
	anl_printf("%3d ",datatemp0[i]);
	anl_printf(" \n");
	anl_printf("P25Q80L Single-Read Finished!\r\n");

	//Dual-SPI mode
	anl_printf("Start Dual-Read P25Q80L....!\r\n");
	P25Q80L_DualRead((uint8_t*)datatemp1,0x000000,256);			 
 	for(i=0; i<256; i++)
	anl_printf("%3d ",datatemp1[i]);
	anl_printf(" \n");
	anl_printf("P25Q80L Dual-Read Finished!\r\n");


	//Quad-SPI mode
	QSPI_REG(SPI_REG_FMT) &= ~(0x3);	// clr effect of Dual-spi REG_FMT cfg.
	anl_printf("Start Quad-Read P25Q80L:\r\n");
	P25Q80L_QuadRead((uint8_t*)datatemp2,0x000000,256);			 
	anl_printf("The Data Readed Is:\r\n");
 	for(i=0; i<256; i++)
	anl_printf("%3d ",datatemp2[i]);
 	anl_printf(" \n");
	anl_printf("P25Q80L Quad-Read Finished!\r\n");

	// data check
	for(i=0; i<256; i++)
		if((datatemp0[i] != datatemp1[i]) | (datatemp1[i] != datatemp2[i]) | (datatemp0[i] != datatemp2[i]))
		{
			anl_printf("FAIL: datas are not same!\r\n");
			return -1;
		}
#endif

	anl_printf("PASS: spi write / read test success!\r\n");
	
 #if 0
	ReadValue=0;
	ReadValue=QSPI_REG(SPI_REG_SCKDIV);
	anl_printf("SPI Divider = %d \r\n",ReadValue);

	ReadValue=0;
	ReadValue=QSPI_REG(SPI_REG_FMT);
	anl_printf("SPI SPI_REG_FMT = %d \r\n",ReadValue);
#endif

	anl_printf("Test finished!\r\n");
    return 0;

}























